export function setTheme() {
  return new Promise((resolve, reject) => {
    // let themeArr = ["custom-sky", "custom-ts"]; // 当前系统已有主题
    const themeName = process.env.NODE_ENV == 'development' ? 'custom-ts' : '' // 模拟获取到的值 随机获取主题
    const body = document.getElementsByTagName('body')[0].classList
    switch (themeName) {
      case 'custom-ts':
        addCssByLink('./static/app-theme/ts.css').then(() => {
          body.remove(body[0])
          body.add('custom-ts')
          resolve()
        })
        break
      default:
        resolve()
        break
    }
  })
}

function addCssByLink(url) {
  var doc = document
  var link = doc.createElement('link')
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('type', 'text/css')
  link.setAttribute('href', url)
  var heads = doc.getElementsByTagName('head')
  if (heads.length) { heads[0].appendChild(link) } else { doc.documentElement.appendChild(link) }
  return new Promise((resolve, reject) => {
    styleOnload(link, function() {
      resolve()
    })
  })
}

function styleOnload(link, callback) {
  // for IE6-9 and Opera
  if (link.attachEvent) {
    link.attachEvent('onload', callback)
    // NOTICE:
    // 1. "onload" will be fired in IE6-9 when the file is 404, but in
    // this situation, Opera does nothing, so fallback to timeout.
    // 2. "onerror" doesn't fire in any browsers!
  }
  // polling for Firefox, Chrome, Safari
  else {
    setTimeout(function() {
      poll(link, callback)
    }, 0) // for cache
  }
}

function poll(link, callback) {
  if (callback.isCalled) {
    return
  }

  var isLoaded = false

  if (/webkit/i.test(navigator.userAgent)) { // webkit
    if (link['sheet']) {
      isLoaded = true
    }
  }
  // for Firefox
  else if (link['sheet']) {
    try {
      if (link['sheet'].cssRules) {
        isLoaded = true
      }
    } catch (ex) {
      // NS_ERROR_DOM_SECURITY_ERR
      if (ex.code === 1000) {
        isLoaded = true
      }
    }
  }

  if (isLoaded) {
    // give time to render.
    setTimeout(function() {
      callback()
    }, 1)
  } else {
    setTimeout(function() {
      poll(link, callback)
    }, 1)
  }
}
